<?php

include DIRETORIO."app/Models/SprintDAO.php";

class C_Sprint{

	protected static $lk = NULL;
	
	public static function init(){
		global $db_Mysql;

		self::$lk = $db_Mysql;	
	}

	public static function getDB(){
		if(self::$lk == NUll)
			self::init();

		return self::$lk;
	}

	public static function getSprints($post){
		$return = null;

		$objSprintDAO	= new SprintDAO(self::getDB());
		$objSprints		= $objSprintDAO->getSprints(0, $_SESSION["PROJECT"]->id);
		
		if(count($objSprints) > 0){
			$html = '<ul class="sprints">';
			
			$dateNow = new DateTime("now");			

			foreach($objSprints as $row){
				$statusSprint = "";
				$completeDataInit = new DateTime($row->completeDateInit);
				$completeDataEnd = new DateTime($row->completeDateEnd);

				if($_SESSION["PROJECT"]->status < 3 && $_SESSION["USER_PERMISSION"] <= 2){
					$buttons = '<a onclick="editSprint('.$row->id.')" href="javascript:void(0);" class="icon edit"><span>editar</span></a>
								<a onclick="deleteSprint('.$row->id.')" href="javascript:void(0);" class="icon delete"><span>deletar</span></a>';
				}else{
					$buttons = '';
				}
				
				if($row->status == 2){
					$statusSprint = "Finalizado";
				}else if($row->completeDateInit >= $dateNow && $dateNow <= $row->completeDataEnd){
					$statusSprint = "Em Desenvolvimento";
				}else if($dateNow > $completeDataEnd){
					$statusSprint = "Atrasado";
				}
				
				$nameTeam = "";
				if($row->team != "")
					$nameTeam = " | Equipe: ".$row->team;

				$html .= '	<li id="sprint_'.$row->id.'">
								<div class="description">
									<span class="title">Sprint '.$row->order.$nameTeam.'</span>
									<span><strong class="countTasks">'.$row->tasks.'</strong> Tarefa(s)</span>
									<span>Período: '.$row->dateBegin.' até '.$row->dateEnd.'</span>
									<span>'.$statusSprint.'</span>
								</div>
								<div class="buttons">
									<a href="'.SITE.'content/kanban/index.php?id='.$row->id.'" class="icon kanban"><span>kanban</span></a>
									<a onclick="loadTasks('.$row->id.')" href="javascript:void(0);" class="icon tasks"><span>tarefas</span></a>
									'.$buttons.'
								</div>								
							</li>';
			}
			
			$html .= '</ul>';
			$return[] = true;
		}else{
			$html = '<ul class="sprints"></ul>';
			$return[] = false;
		}
	
		$return[] = $html;	
		return json_encode($return);
	}

	public static function newSprint(){
		$return = null;

		$objTeamDAO	= new TeamDAO(self::getDB());
		$objTeams	= $objTeamDAO->getTeams();

		$selectTeams = "";
		if(count($objTeams) > 0){
			foreach($objTeams as $row){
				if($row->users > 0)
					$selectTeams .= '<option value="'.$row->id.'">'.$row->name.'</option>';
			}
		}

		$html = file_get_contents(TEMPLATES."sprint.html");		
		$html = str_replace("[TITLE]","Novo Sprint",$html);
		$html = str_replace("[ID_SPRINT]",0,$html);
		$html = str_replace("[SITE]",SITE,$html);
		$html = str_replace("[LIST_TEAMS]",$selectTeams,$html);
		$html = str_replace("[DATE_BEGIN]",date("d/m/Y"),$html);
		$html = str_replace("[DATE_END]",date("d/m/Y"),$html);
		
		$tempDate = explode("/",$_SESSION["PROJECT"]->dateBegin);
		$limiteDates["dateBegin"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
		$tempDate = explode("/",$_SESSION["PROJECT"]->dateEndEstimated);
		$limiteDates["dateEndEstimated"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];

		if($html <> ""){
			$return = array(true,$html,$limiteDates);
		}else{
			$return = array(false,"Não foi possível buscar o Sprint!");
		}

		return json_encode($return);
	}

	public static function editSprint($post){
		$return = null;
		
		$objSprintDAO	= new SprintDAO(self::getDB());
		$objSprint		= $objSprintDAO->getSprints((int)$post[id], $_SESSION["PROJECT"]->id);

		$objTeamDAO	= new TeamDAO(self::getDB());
		$objTeams	= $objTeamDAO->getTeams();

		$selectTeams = "";
		if(count($objTeams) > 0){
			foreach($objTeams as $row){
				if($objSprint[0]->idTeam == $row->id)
					$selected = " selected";
				else
					$selected = "";
				$selectTeams .= '<option value="'.$row->id.'"'.$selected.'>'.$row->name.'</option>';
			}
		}

		$html = file_get_contents(TEMPLATES."sprint.html");
		$html = str_replace("[TITLE]","Editar Sprint ".$objSprint[0]->order,$html);
		$html = str_replace("[ID_SPRINT]",$objSprint[0]->id,$html);
		$html = str_replace("[SITE]",SITE,$html);
		$html = str_replace("[LIST_TEAMS]",$selectTeams,$html);
		$html = str_replace("[DATE_BEGIN]",$objSprint[0]->dateBegin,$html);
		$html = str_replace("[DATE_END]",$objSprint[0]->dateEnd,$html);

		$tempDate = explode("/",$_SESSION["PROJECT"]->dateBegin);
		$limiteDates["dateBegin"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
		$tempDate = explode("/",$_SESSION["PROJECT"]->dateEndEstimated);
		$limiteDates["dateEndEstimated"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];

		if($html <> ""){
			$return = array(true,$html,$limiteDates);
		}else{
			$return = array(false,"Não foi possível editar o Sprint!");
		}

		return json_encode($return);
	}

	public static function saveSprint($post){
		$return = null;
		$id		= 0;
		
		if(count($post) > 0){
			$objSprintDAO	= new SprintDAO(self::getDB());		
			$objSprint		= new Sprint();

			foreach($post as $key => $value){
				if(stristr($key,"date")){
					$tempDate = explode("/",$value);
					$value = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
				}
				$objSprint->$key = $value;
			}
						
			if($objSprint->id > 0){		
				$objSprintDAO->save($objSprint);
				$id = $objSprint->id;
			}else{
				$objSprint->idUserCreator	= $_SESSION["USER"]->id;
				$objSprint->idProject		= $_SESSION["PROJECT"]->id;
				$objSprint->status			= 1; //Ativa
				$objSprint->order			= $objSprintDAO->nextSprint($objSprint->idProject);
				$id = $objSprintDAO->save($objSprint);
			}
		}
		

		if($id > 0){
			$return =  array(true,"<i>\"Sprint ". $objSprint->order ."\"</i> salvo com sucesso.");
		}else{
			$return =  array(false,"Não foi possível salvar o Sprint!");
		}


		return json_encode($return);
	}

	public static function getTaskSprints(){
		$return = array(false,"Não foi possível atualizar os Sprints!");

		$objSprintDAO = new SprintDAO(self::getDB());
		$result = $objSprintDAO->getTaskSprints($_SESSION["PROJECT"]->id);

		if(count($result) > 0){
			$return = array(true,$result);
		}

		return json_encode($return);
	}

	public static function getSelectSprints($post){
		$return = null;

		$objSprintDAO	= new SprintDAO(self::getDB());
		$objSprints		= $objSprintDAO->getSprints(0, $_SESSION["PROJECT"]->id);
		$idSprint		= (int)$post["id"];
		
		if($idSprint == 0){
			$objSprint	= $objSprintDAO->actualSprint($_SESSION["PROJECT"]->id);
			$idSprint   = $objSprint->id; 
		}	
				
		if(count($objSprints) > 0){
			$selectSprints = '<select id="actual_sprint">';
			foreach($objSprints as $row){

				$selected = $row->id == $idSprint?" selected":"";
				$selectSprints .= '<option value="'.$row->id.'"'.$selected.'>Sprint '.$row->order.'</option>';
			}
			$selectSprints .= '</select>';
		}

		return json_encode(array(true, $selectSprints));
	}

	public static function deleteSprint($post){	
		$objSprintDAO	= new SprintDAO(self::getDB());
		$idSprint		= (int)$post['id'];
		$result			= 0;

		if($idSprint > 0)
			$result = $objSprintDAO->deleteSprint($idSprint,$_SESSION["PROJECT"]->id);

		if($result > 0)
			$return = array(true,"Sprint excluído com sucesso.");
		else if($result == -1)
			$return = array(false,"Erro, existem Tarefas vinculadas a este Sprint!");
		else
			$return = array(false,"Erro, não foi possível excluir o Sprint!");

		return json_encode($return);
	}
}
?>